package com.company.ems.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

public class AuthenticationFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("AuthenticationFilter initialized");
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 防止响应已经提交的情况下尝试重定向
        if (httpResponse.isCommitted()) {
            chain.doFilter(request, response);
            return;
        }
        
        String path = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        
        // 不需要登录验证的路径
        if (path.equals("/login.jsp") || path.equals("/login") || 
            path.equals("/") || path.startsWith("/css/") || 
            path.startsWith("/js/") || path.startsWith("/error/") ||
            path.equals("/logout")) {
            chain.doFilter(request, response);
            return;
        }
        
        HttpSession session = httpRequest.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            // 使用绝对路径重定向
            String redirectUrl = httpRequest.getContextPath() + "/login.jsp";
            httpResponse.sendRedirect(redirectUrl);
            return;
        }
        
        // 设置响应头，防止缓存
        httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        httpResponse.setHeader("Pragma", "no-cache");
        httpResponse.setDateHeader("Expires", 0);
        
        chain.doFilter(request, response);
    }
    
    @Override
    public void destroy() {
        System.out.println("AuthenticationFilter destroyed");
    }
}